package com.yupi.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.picture.PictureQueryRequest;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.service.PictureService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> search(PictureQueryRequest pictureQueryRequest, int current, long size) {
        String searchText = pictureQueryRequest.getSearchText();
        int currentIndex= (int) ((current-1)* size);
        Document doc = null;
        try {
            doc = Jsoup.connect(String.format("https://cn.bing.com/images/search?q=%s&first=%s",searchText,currentIndex)).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据获取异常");
        }
//        System.out.println(doc);
        Elements newsHeadlines = doc.select(".iuscp.isv");
        ArrayList<Picture> pictures = new ArrayList<>();
        for (Element element : newsHeadlines) {
            String m = element.select(".iusc").get(0).attr("m");
            String title = element.select(".inflnk").get(0).attr("aria-label");
            Map map = JSONUtil.toBean(m, Map.class);
            String murl = (String) map.get("murl");
            Picture picture = new Picture();
            picture.setTitle(title);
            picture.setUrl(murl);
            pictures.add(picture);
        }
        Page<Picture> picturePage = new Page<>();
        picturePage.setRecords(pictures);
        return picturePage;
    }
}
